<template>
	<view class="container">
		<view class="personal">
			<!-- 页面头部 -->
			<view class="header">
				<view class="title">
					<text>获取您的昵称、头像</text>
				</view>
				<view class="sub-title">
					<text>填写您的微信头像和昵称，以便获得更好的体验</text>
				</view>
			</view>
			<!-- 表单组件 -->
			<view class="login-form">
				<view class="form-item">
					<view class="form-item--label">头像</view>
					<button class="btn-normal" open-type="chooseAvatar" @click="onClickAvatar()"
						@chooseavatar="onChooseAvatar">
						<cg-image type="static" v-if="staticImg" :src="avatarUrl" width="100px"
							height="100px"></cg-image>
						<cg-image v-else :src="avatarUrl" width="100px" height="100px"></cg-image>
					</button>
				</view>
				<view class="form-item">
					<view class="form-item--label">昵称</view>
					<input class="form-item--input" type="nickname" v-model="form.nickName" maxlength="30"
						placeholder="请输入微信昵称" @input="onInputNickName" @blur="onInputNickName" />
				</view>
				<div class="form-item">
					<view class="form-item--label">手机号</view>
					<button class="btn-normal" open-type="getPhoneNumber"
						@getphonenumber="handelMpWeixinMobileLogin($event)" @click="clickPhoneNumber">
						<view class="wechat-auth-container">

							<!-- <u-icon name="weixin-circle-fill" :color="themeColor" size="112rpx"></u-icon> -->
							<text class="title">点击获取手机号</text>
						</view>
					</button>
				</div>

			</view>
			<!-- 操作按钮 -->
			<view class="login-btn">
				<view class="button" :class="{ disabled }" @click="handleSubmit()">确认</view>
			</view>
			<view class="no-login-btn">
				<view class="button" @click="$CGRouter.go(1)">暂不登录</view>
			</view>
		</view>
		<!-- <view v-if="isPersonal === false" class="authorize">
      <view class="store-info">
        <view class="header">
          <image class="image" :src="storeInfo && storeInfo.image_url ? storeInfo.image_url : '/static/default-logo.png'"></image>
        </view>
      </view>
      <view class="auth-title">申请获取以下权限</view>
      <view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
      <view class="login-btn">
        <view class="button" :class="{ disabled }" @click="handleLogin()">一键登录</view>
      </view>
      <view class="no-login-btn">
        <view class="button" @click="handleCancel()">暂不登录</view>
      </view>
    </view> -->

	</view>
</template>

<script>
	import store from '@/store'
	import * as LoginApi from '@/api/common'
	import {
		upload
	} from '@/api/common'
	import utils from '@/common/utils/utils'
	import * as Verify from '@/common/utils/verify';
	import weixin from '@/common/utils/weixin.js'


	export default {

		data() {
			return {
				// 商城基本信息
				storeInfo: undefined,
				// 是否需要填写用户昵称和头像
				isPersonal: undefined,
				// 微信小程序登录凭证 (code)
				// 提交到后端，用于换取openid
				code: '',
				// 按钮禁用
				disabled: false,
				// 头像路径 (用于显示)
				avatarUrl: '/default-avatar.png',
				staticImg: false,
				// 临时图片 (用于上传)
				tempFile: undefined,
				// 表单数据
				form: {
					avatarId: null,
					nickName: ''
				},
			}
		},

		created() {
			// 获取商城基本信息
			// this.getStoreInfo()
			// 请求后端是否需要填写昵称头像 (微信小程序端)
			this.getIsPersonal()
		},

		methods: {
			// 按钮点击事件: 获取微信手机号按钮
			// 实现目的: 在getphonenumber事件触发之前获取微信登录code
			// 因为如果在getphonenumber事件中获取code的话,提交到后端的encryptedData会存在解密不了的情况
			async clickPhoneNumber() {
				this.code = await this.getCode()
			},

			// 微信授权获取手机号一键登录
			// getphonenumber事件的回调方法
			async handelMpWeixinMobileLogin({
				detail
			}) {
				
				if (detail.errMsg != 'getPhoneNumber:ok') {
					console.log('微信授权获取手机号失败', detail)
					return
				}
				if (detail.errMsg == 'getPhoneNumber:ok') {
					this.isLoading = true
					store.dispatch('LoginMpWxMobile', {
							code: this.code,
							encryptedData: detail.encryptedData,
							iv: detail.iv,
							isParty: detail.isParty,
							partyData: detail.partyData
						})
						.then(result => {
							// 显示登录成功
							this.$dialog.toast(result.message)
							// 相应全局事件订阅: 刷新上级页面数据
							uni.$emit('syncRefresh', true)
							// 跳转回原页面
							this.$CGRouter.go(1, 2000)
						})
						.catch(err => {
							const resultData = err.result.data
							// 显示错误信息
							if (utils.isEmpty(resultData)) {
								this.$dialog.toast(err.result.message)
							}
							// 跳转回原页面
							if (resultData.isBack) {
								this.$CGRouter.go(1, 2000)
							}
						})
						.finally(() => this.isLoading = false)
				}
			},
			/**
			 * 请求后端是否需要填写昵称头像 (微信小程序端)
			 *  - 条件1: 后台开启了填写微信头像和昵称
			 *  - 条件2: 用户首次注册或者已注册但未填写过信息
			 */
			async getIsPersonal() {
				
				LoginApi.isPersonalMpweixin({
						code: await this.getCode()
					})
					.then(result => this.isPersonal = result.data.isPersonalMpweixin)
			},

			// 获取code
			// https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
			async getCode() {
				try {
					const {
						code
					} = await weixin.wxLogin();
					return code
				} catch (err) {
					//TODO handle the exception
					console.log('err', err);
				}

			},

			// 绑定昵称输入框 (用于微信小程序端快速填写昵称能力)
			onInputNickName({
				detail
			}) {
				console.log(detail)
				if (detail.value) {
					this.form.nickName = detail.value
				}
			},

			// 点击头像按钮事件
			onClickAvatar() {
				// #ifdef MP-WEIXIN
				return
				// #endif
				this.chooseImage()
			},

			// 选择头像事件 - 仅限微信小程序
			onChooseAvatar({
				detail
			}) {
				this.staticImg = false;
				this.avatarUrl = detail.avatarUrl
				this.tempFile = {
					path: this.avatarUrl
				}
			},

			// 选择图片
			chooseImage() {
				this.$utils.chooseImage().then(res => {
					this.tempFile = tempFiles[0]
					this.avatarUrl = this.tempFile.path
				})

			},

			// 上传图片
			uploadFile() {
				
				return upload([this.tempFile], false)
					.then(fileIds => {
						this.form.avatarId = fileIds[0]
						this.tempFile = null
						return true
					})
					.catch(() => {
						return false
					})
			},

			// 确认提交头像昵称
			async handleSubmit() {
				
				console.log('handleSubmit', this.form, this.tempFile)
				if (this.disabled === true) {
					return
				}
				if (this.tempFile === undefined || utils.isEmpty(this.form.nickName)) {
					this.$dialog.toast('请填写头像和昵称~')
					return
				}
				// 按钮禁用
				this.disabled = true
				// 先上传头像图片
				if (!await this.uploadFile()) {
					this.$dialog.toast('很抱歉，头像上传失败')
					this.disabled = false
					return
				}
				// 提交到后端
				this.onAuthSuccess({
					nickName: this.form.nickName,
					avatarId: this.form.avatarId
				})
			},

			// 一键登录按钮点击事件
			handleLogin() {
				// this.onAuthSuccess({ nickName: '微信用户', avatarUrl: '' })
				this.onAuthSuccess({})
			},

			// 授权成功事件
			// 这里分为两个逻辑:
			// 1.将code和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
			// 2.如果不存在该用户, 则显示注册页面, 需填写手机号
			// 3.如果后端报错了, 则显示错误信息
			async onAuthSuccess(userInfo) {
				
				// 提交到后端
				store.dispatch('LoginMpWx', {
						partyData: {
							code: await this.getCode(),
							oauth: 'MP-WEIXIN',
							userInfo
						}
					})
					.then(result => {
						// 一键登录成功
						this.$dialog.toast(result.message)
						// 相应全局事件订阅: 刷新上级页面数据
						uni.$emit('syncRefresh', true)
						// 跳转回原页面
						this.$CGRouter.go(1, 2000)
					})
					.catch(err => {
						const resultData = err.result.data
						// 显示错误信息
						if (utils.isEmpty(resultData)) {
							this.$dialog.toast(err.result.message)
						}
						// 跳转回原页面
						if (resultData.isBack) {
							$this.$CGRouter.go(1, 2000)
						}
						// 判断还需绑定手机号
						if (resultData.isBindMobile) {
							this.onEmitSuccess(userInfo)
						}
					})
			},

			// 将oauth提交给父级
			// 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
			async onEmitSuccess(userInfo) {
				
				this.$emit('success', {
					oauth: 'MP-WEIXIN', // 第三方登录类型: MP-WEIXIN
					code: await this.getCode(), // 微信登录的code, 用于换取openid
					userInfo // 微信用户信息
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 60rpx;
		font-size: 32rpx;
		background: #fff;
		min-height: 100vh;
	}

	/* 无样式button (用于伪submit) */

	.btn-normal {
		display: block;
		margin: 0;
		padding: 0;
		line-height: normal;
		background: none;
		border-radius: 0;
		box-shadow: none;
		border: none;
		font-size: unset;
		text-align: unset;
		overflow: visible;
		color: inherit;
	}

	.btn-normal:after {
		border: none;
	}

	.btn-normal.button-hover {
		color: inherit;
	}

	button:after {
		content: none;
		border: none;
	}


	.personal {

		// 页面头部
		.header {
			padding-top: 120rpx;
			margin-bottom: 60rpx;

			.title {
				margin-bottom: 20rpx;
				color: #191919;
				font-size: 44rpx;
			}

			.sub-title {
				margin-bottom: 70rpx;
				color: #b3b3b3;
				font-size: 28rpx;
			}
		}

		.login-form {
			margin-bottom: 90rpx;
		}

		// 输入框元素
		.form-item {
			display: flex;
			align-items: center;
			padding: 18rpx;
			border-bottom: 1rpx solid #f3f1f2;
			margin-bottom: 30rpx;
			min-height: 96rpx;

			&--label {
				min-width: 150rpx;
				font-size: 28rpx;
				line-height: 50rpx;
			}

			&--input {
				font-size: 28rpx;
				letter-spacing: 1rpx;
				flex: 1;
				height: 100%;
			}

			&--parts {
				min-width: 100rpx;
			}

		}

	}

	.authorize {
		.store-info {
			padding: 80rpx 0 48rpx;
			border-bottom: 1rpx solid #e3e3e3;
			margin-bottom: 72rpx;
			text-align: center;

			.header {
				width: 190rpx;
				height: 190rpx;
				border: 4rpx solid #fff;
				margin: 0 auto 0;
				border-radius: 50%;
				overflow: hidden;
				box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);

				.image {
					display: block;
					width: 100%;
					height: 100%;
				}
			}
		}

		.auth-title {
			color: #585858;
			font-size: 34rpx;
			margin-bottom: 40rpx;
		}

		.auth-subtitle {
			color: #888;
			margin-bottom: 88rpx;
			font-size: 28rpx;
		}

	}

	.login-btn {
		margin-bottom: 20rpx;

		.button {
			width: 100%;
			height: 86rpx;
			background: #04FF0B;
			color: #fff;
			font-size: 30rpx;
			border-radius: 80rpx;
			letter-spacing: 5rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			// 禁用按钮
			&.disabled {
				opacity: 0.6;
			}
		}
	}


	.no-login-btn {

		.button {
			height: 86rpx;
			background: #dfdfdf;
			color: #fff;
			font-size: 30rpx;
			border-radius: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>